package com.xiang.utils.aggs;

import com.xiang.config.EsConfig;
import com.xiang.utils.CreateDoc;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.ParsedCardinality;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 查询去重后的数据
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class CardinalityQueryCount {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(CreateDoc.class);

    /**
     * 去重查询
     */
    @Test
    public void cardinalityQuery() throws IOException {
        SearchRequest request = new SearchRequest(EsConfig.INDEX_NAME);
        // 封装查询DSL
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.cardinality("agg").field("age"));
        request.source(builder);
        // 执行查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 获取返回结果
        Aggregation agg = response.getAggregations().get("agg");
        logger.info("查询结果：{}", ((ParsedCardinality) agg).getValueAsString());
    }

}
